import Quartz
from Quartz import CGWindowListCopyWindowInfo, kCGWindowListOptionOnScreenOnly, kCGNullWindowID

# 获取所有窗口信息
window_list = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID)
from time import sleep

import pyautogui
import pytesseract
from PIL import Image


def get_pass_window():
    # 使用CGWindowListCopyWindowInfo获取窗口信息
    window_info = Quartz.CGWindowListCopyWindowInfo(
        Quartz.kCGWindowListOptionOnScreenOnly | Quartz.kCGWindowListExcludeDesktopElements,
        Quartz.kCGNullWindowID
    )
    for window in window_info:
        window_id = window.get('kCGWindowNumber', 0)
        window_title = window.get('kCGWindowName', '')
        window_owner = window.get('kCGWindowOwnerName', '')
        window_bounds = window.get('kCGWindowBounds', {})

        # 只考虑有标题的可见窗口
        if window_title and window_bounds:
            if window_title == '验证码' and window_owner == '密码扩展帮助程序':
                return {
                    'id': window_id,
                    'title': window_title,
                    'owner': window_owner,
                    'bounds': window_bounds
                }

    return None


if __name__ == '__main__':
    print("start ok!")
    while True:
        sleep(0.5)
        window = get_pass_window()
        if window is None:
            continue

        bounds = window['bounds']
        # 假设通过前面获取坐标步骤得到以下值，实际使用时请根据真实情况调整
        x = bounds['X']
        y = bounds['Y']
        width = bounds['Width']
        height = bounds['Height']

        print(bounds)

        # 截取指定区域
        screenshot = pyautogui.screenshot(region=(int(x + 160), int(y + 100), int(width - 250), int(50)))
        screenshot.save('screenshot.png')
        image = Image.open('screenshot.png')
        #
        test = pytesseract.image_to_string(image, lang='eng').replace('\n', '').replace(' ', '')
        print(f"input {test} !")
        if test.isdigit():
            for p in test:
                pyautogui.press(str(p))
